﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Data;
using System.Text;
using MadeInPortugal.Class;
using MadeInPortugalWebApplication.WebControl;
using MadeInPortugal;

namespace MadeInPortugalWebApplication.WebControl
{
    //public delegate void TagSelectedEventHandler(object sender, int tagId);
    //public delegate void ItemDeleteEventHandler(object sender, int itemId);
    //public delegate void ItemEditEventHandler(object sender, int itemId);
    //public delegate void ItemInfoEventHandler(object sender, int itemId);
    //public delegate void ItemFavouriteEventHandler(object sender, int itemId);
    //public delegate void ItemMoveEventHandler(object sender, string itemsOrder);

    public delegate void Page2ChangedEventhandler();
    public partial class FavoritesListWC : System.Web.UI.UserControl
    {
        public event TagSelectedEventHandler OnTagSelected;
        public event ItemDeleteEventHandler OnDeleteItem;
        public event ItemEditEventHandler OnEditItem;
        public event ItemFavouriteEventHandler OnFavouriteItem;

        public event Page2ChangedEventhandler OnPageChange;

        //private MyDesktopBusiness.MyDesktopService _service = new MyDesktopBusiness.MyDesktopService();


        ArrayList itemsList = new ArrayList();
        DataTable dtPages;
        int pageSize = 5;
        int UserId = 0;
        String UserType;


        public int CurrentPage
        {
            get { return int.Parse(hfPageNumber.Value); }
            set { hfPageNumber.Value = value.ToString(); ; }
        }

        private int LastPage
        {
            get
            {
                int lastpage = itemsList.Count / PageSize;

                lastpage += (itemsList.Count % PageSize == 0) ? 0 : 1;

                lastpage = (lastpage == 0) ? 1 : lastpage;

                return lastpage;
            }
        }

        public int PageSize
        {
            get { return pageSize; }
            set { pageSize = value; }
        }

        public bool openNewPage
        {
            get;
            set;
        }

        public string Target
        {
            get { if (openNewPage) return "_blank"; return "_self"; }
            //set { Target = value; }
        }


        public bool AllowDelete
        {
            get;
            set;
        }

        public bool AllowMove
        {
            get;
            set;
        }

        public bool AllowFavourite
        {
            get;
            set;
        }

        public bool AllowEdit
        {
            get;
            set;
        }
        protected void itemList_OnDeleteItem(object sender, int itemId)
        {
            Favorites fav = new Favorites();
            fav.Delete(new Favorites(){ProductId= itemId,UserId= int.Parse(Session["UserId"].ToString())});
        }

        public Product[] ItemsList
        {
            get { return (Product[])itemsList.ToArray(typeof(Product)); }
            set
            {
                if (itemsList == null)
                    itemsList = new ArrayList();
                itemsList.Clear();
                itemsList.AddRange(value);
            }
        }

        public DataTable DtPages
        {
            get
            {
                if (dtPages == null)
                {
                    dtPages = new DataTable();
                    dtPages.Columns.Add("Class");
                    dtPages.Columns.Add("PageNumber");
                }
                return dtPages;
            }
            set
            {
                if (value != null)
                    dtPages = value;
            }
        }



        private void CheckUser()
        {
            if (Session["UserType"] != null)
                UserType = Session["UserType"].ToString();
            if (Session["UserId"] != null)
                int.TryParse(Session["UserId"].ToString(), out UserId);
        }

        private void SortItems()
        {
            DataTable sort = new DataTable();
            sort.Columns.Add("ID");
            sort.Columns.Add("ProductName");
            sort.Columns.Add("PriorityFinal");

            foreach (Product item in itemsList)
            {
                DataRow row = sort.NewRow();
                row["ID"] = item.Id.ToString();
                row["ProductName"] = item.ProductName;
                row["PriorityFinal"] = item.PriorityFinal;
                sort.Rows.Add(row);
            }


            sort.DefaultView.Sort = "PriorityFinal Desc";
            itemsList.Clear();
            for (int i = 0; i < sort.DefaultView.Count; i++)
            {
                itemsList.Add(new Product() { Id = int.Parse(sort.DefaultView[i]["ID"].ToString()), ProductName = sort.DefaultView[i]["ProductName"].ToString() });
            }
        }

        //private void FillProductsByEnterprise(string idString, Product Products)
        //{
        //    Product[] ProductsArray = Products.GetByTagId(int.Parse(idString));
        //    //DataTable sort = new DataTable();
        //    foreach (Product item in ProductsArray)
        //    {
        //        //sort.Columns.Add(
        //        itemsList.Add((Product)item);
        //    }


            //sort.DefaultView.Sort = "PriorityFinal Desc";
            //itemsList.Add(sort.DefaultView);
            //itemList.DataSource = Products.GetByTagId(int.Parse(idString));
            //itemList.ItemDataBound += new RepeaterItemEventHandler(itemList_ItemDataBound);
        //}

        //  void itemList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        //{
            //if (AllowFavourite && e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            //{
            //    Product item = e.Item.DataItem as Product;

            //    if (item != null)
            //    {
            //        try
            //        {
            //            Product userItem = _service.ReadUserItem(Product.GetCurrentUserNumber(Context), item);

            //            if (userItem.UserItemID > 0)
            //            {
            //                LinkButton favoriteLink = e.Item.FindControl("favouriteItem") as LinkButton;
            //                favoriteLink.CssClass = "action favorite_selected";

            //            }
            //        }
            //        catch (Exception)
            //        { }
            //    }
            //}
        //}

        protected override void OnLoad(EventArgs e)
        {
            string prevPage = "";
            if (!IsPostBack)
            {
                CheckUser();
            }

            string idString = Request.QueryString["Id"];

            Product Products = new Product();

            base.OnInit(e);
            DtPages = (DataTable)ViewState["pages"];
            Product product = new Product();

            Favorites fav = new Favorites();
            Product[] prodArray = fav.GetFavorites(new Favorites() { UserId = int.Parse(Session["UserId"].ToString()) });

            foreach (Product Product in prodArray)
            {
                itemsList.Add((Product)Product);
            }


            SortItems();
            base.OnLoad(e);
            if (itemsList != null)
            {
                int intermCount = ((CurrentPage) * PageSize > itemsList.Count) ? (itemsList.Count - (CurrentPage - 1) * PageSize) : PageSize;
                itemList.DataSource = itemsList.GetRange((CurrentPage - 1) * PageSize, intermCount);
                itemList.DataBind();


                BuildPagination();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (itemsList != null)
            {
                int intermCount = ((CurrentPage) * PageSize > itemsList.Count) ? (itemsList.Count - (CurrentPage - 1) * PageSize) : PageSize;
                itemList.DataSource = itemsList.GetRange((CurrentPage - 1) * PageSize, intermCount);
                itemList.DataBind();

                BuildPagination();
                BuildPreviousNextButtons();
            }
            if (IsPostBack)
            {
                string strSetViewJs = @"    
            /**
	         * Set the user view 
	         */
          
        
	        if($.cookie('listView')!=null){		
		        itemListChanger($.cookie('listView'))
	        }
	        else{
		        itemListChanger('bigIcons')
	        }

 $('#itemList').sortable({
                cursor: 'crosshair',
                opacity: 0.5,
                handle: 'a.move',
                update: function(event, ui) { updateListPositions(this); }
            });
            $('#itemList').disableSelection();
            ";

                ScriptManager.RegisterStartupScript(itemList, itemList.GetType(), "setUserView", strSetViewJs, true);
            }
            ViewState["pages"] = DtPages;
        }

        protected void ChangePage_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName.Equals("goPage"))
            {
                int pageSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out pageSelected))
                {
                    if (OnPageChange != null)
                        OnPageChange();
                    CurrentPage = pageSelected;
                }
            }
        }

        protected void RepeaterChangePage_Command(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("goPage"))
            {
                int pageSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out pageSelected))
                {
                    if (OnPageChange != null)
                        OnPageChange();
                    CurrentPage = pageSelected;
                }
            }
        }

        protected void RepeaterChangeTag_Command(object sender, CommandEventArgs e)
        {
            //if (e.CommandName.Equals("setTag"))
            //{
            //    int tagSelected = 1;
            //    if (int.TryParse(e.CommandArgument.ToString(), out tagSelected))
            //    {
            //        if (OnTagSelected != null)
            //            OnTagSelected(this, tagSelected);
            //    }
            //}
        }

        protected void RepeaterItem_Command(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteItem"))
            {
                int itemSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out itemSelected))
                {
                    if (OnDeleteItem != null)
                        OnDeleteItem(this, itemSelected);
                }
            }
            if (e.CommandName.Equals("editItem"))
            {
                int itemSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out itemSelected))
                {
                    if (OnEditItem != null)
                        OnEditItem(this, itemSelected);
                }
            }
            if (e.CommandName.Equals("favouriteItem"))
            {
                int itemSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out itemSelected))
                {
                    if (OnFavouriteItem != null)
                        OnFavouriteItem(this, itemSelected);
                }
            }
        }

        private void BuildPreviousNextButtons()
        {
            if (CurrentPage == 1)
            {
                previousPage.Visible = false;
            }
            else
            {
                previousPage.CommandArgument = (CurrentPage - 1).ToString();
                previousPage.Visible = true;
            }

            if (CurrentPage == LastPage)
            {
                nextPage.Visible = false;
            }
            else
            {
                nextPage.CommandArgument = (CurrentPage + 1).ToString();
                nextPage.Visible = true;
            }
        }

        private void BuildPagination()
        {
            DtPages.Clear();
            if (itemsList.Count > PageSize)
            {
                int intermediateCount = 0;
                while (intermediateCount < itemsList.Count)
                {
                    int pageNr = intermediateCount / PageSize + 1;

                    DataRow dr = DtPages.NewRow();
                    dr["Class"] = (pageNr == CurrentPage ? "current" : string.Empty);
                    dr["PageNumber"] = pageNr;
                    DtPages.Rows.Add(dr);

                    intermediateCount += PageSize;
                }

                paginationList.DataSource = DtPages;
                paginationList.DataBind();
            }
        }

        protected void nextPage_Click(object sender, EventArgs e)
        {

        }
    }
}
